<template>
    <div>
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
            <!-- 添加按钮 -->
            <el-button type="primary" size="default" :icon="Plus" @click="addTrademark"  v-visite="'btn.Trademark.add'">添加</el-button>
            <!-- table表格 -->
            <el-table border style="margin: 10px 0;" :data="tmObj.records" v-loading="loading"
                element-loading-text="Loading..." element-loading-background="rgba(122, 122, 122, 0.1)">
                <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                <el-table-column label="品牌名称" prop="tmName"></el-table-column>
                <el-table-column label="品牌LOGO">
                    <template #="{row,$index}">
                        <a :title="row.tmName">
                            <img :src="row.logoUrl" alt="" style="width: 100px;height:80px">
                        </a>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #="{row,$index}">
                        <el-button type="warning" size="small" :icon="Edit" @click="updateTrademark(row)"></el-button>

                        <el-popconfirm :title="`你确定删除${row.tmName}吗?`" @confirm="deleteTrademark(row)">
                            <template #reference>
                                <el-button type="danger" size="small" :icon="Delete">
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination @current-change="getTrademarkList" @size-change="sizeHandler"
                v-model:current-page="currentPage" :page-sizes="[1,3,5,7]" v-model:page-size="pageSize"
                layout="prev, pager, next, jumper,->,sizes,total" :total="tmObj.total" background :pager-count="7">
            </el-pagination>

            <!-- 对话框 -->
            <el-dialog v-model="dialogFormVisible" :title="tmParams.id?'修改品牌':'添加品牌'" draggable>
                <el-form style="width:80%" :model="tmParams" :rules="rules" ref="formRef">
                    <el-form-item label="品牌名称" label-width="90px" prop="tmName">
                        <el-input v-model="tmParams.tmName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="品牌LOGO" prop="logoUrl">
                        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="addOrUpdateTrademark">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>

    </div>
</template>

<script setup lang="ts">
// 引入icon图标相关的组件
import type { trademarkData, infoResponseData } from '@/api/product/trademark/model/trademark';
import { reqTrademarkList, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark/trademark';
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'
// 提示信息组件
import { ElMessage } from 'element-plus'
// 上传图片需要的钩子
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { onMounted, reactive, ref, nextTick } from 'vue';

// 存储当前第几页的响应式数据
let currentPage = ref<number>(1)
// 存储每一页展示几条数据的响应式
let pageSize = ref<number>(3)
// 存储品牌列表数据
let tmObj = reactive<infoResponseData>({
    records: [],
    total: 0
})
// 定义是否显示加载效果
let loading = ref<boolean>(false)

// 控制对话框的显示/隐藏
let dialogFormVisible = ref<boolean>(false)

// 定义添加/修改所需要的参数
let tmParams = reactive<trademarkData>({
    tmName: '',
    logoUrl: ''
})

// 获取当前表单实例
let formRef = ref<FormInstance>()

// 表单校验规则
const rules = reactive<FormRules>({
    tmName: [
        { required: true, message: '品牌内容不能为空', trigger: 'blur' },
        { required: true, min: 2, max: 10, message: '品牌内容大小为2-10', trigger: 'change' },
    ],
    logoUrl: [
        { required: true, message: '请上传合适的logo图片' }
    ]
})

// 组件挂载
onMounted(() => {
    // 发请求
    getTrademarkList()
})

// 获取品牌数据列表
const getTrademarkList = async (page: number = 1) => {
    // 请求前显示加载效果
    loading.value = true
    // 整理数据
    currentPage.value = page
    let result = await reqTrademarkList(currentPage.value, pageSize.value)
    // console.log(result);
    tmObj.records = result.records
    tmObj.total = result.total
    // 请求成功服务器返回数据关闭加载效果
    loading.value = false
}
// 设置分页器一页展示几条数据
const sizeHandler = (limit: number) => {
    pageSize.value = limit
    // 重新发请求
    getTrademarkList()
}
// 上传图片成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // console.log(response);
    tmParams.logoUrl = response.data
}
// 上传前需要的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // 图片相关的信息
    // 约束图片的类型
    if (rawFile.type == 'image/jpeg' || rawFile.type == '/image/png' || rawFile.type == 'image/gif') {
        // 约束图片的大小
        if (rawFile.size / 1024 / 1024 <= 5) {
            return true;
        }
    } else {
        Message.error('图片不符合要求')
        return false;
    }
}
// 点击添加
const addTrademark = () => {
    dialogFormVisible.value = true
    // 清空数据
    tmParams.tmName = ''
    tmParams.logoUrl = ''
    tmParams.id = ''
    //每一次点击添加按钮重置表单验证信息[上一次验证信息清空]
    // formRef.value.resetFields();

    //nextTick:当响应式数据发生变化[页面重新渲染],获取更新后的DOM
    nextTick(() => {
        formRef.value?.resetFields();
    });
}

//点击确定 添加/修改品牌数据
const addOrUpdateTrademark = async () => {
    //触发el-form组件实例的validate方法
    //全部字段进行校验
    formRef.value?.validate(async (success) => {
        if (success) {
            // 发请求
            await reqAddOrUpdateTrademark(tmParams)
            // 关闭对话框
            dialogFormVisible.value = false
            // 重新获取列表
            getTrademarkList(tmParams.id ? currentPage.value : 1)
            ElMessage({
                message: tmParams.id ? '修改品牌成功' : '添加品牌成功',
                type: 'success',
            })
        } else {
            ElMessage({
                type: 'error',
                message: '请完成所有信息'
            })
        }
    })

}

// 点击修改 获取当前数据
const updateTrademark = (row: trademarkData) => {
    dialogFormVisible.value = true

    // 重置表单校验数据
    nextTick(() => {
        formRef.value?.resetFields();
        tmParams.tmName = row.tmName
        tmParams.logoUrl = row.logoUrl
        tmParams.id = row.id
    });
}

// 点击删除 删除品牌
const deleteTrademark = async (row: trademarkData) => {
    try {
        await reqDeleteTrademark(row)
        getTrademarkList(currentPage.value)
        ElMessage({
            type:'success',
            message:`删除${row.tmName}成功`
        })
    } catch (error) {

    }

}

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>